<script setup lang="ts">
import { ref, watch, toRef, onMounted } from "vue";
import { listDevicesByMeasure, listDeviceStatus } from "@/api/deviceApi";
import { defaultSetting } from "./DefaultConfig";
import { ElMessage } from "element-plus";
import { addPlatformDevice } from "@/api/LabPlatformApi";

const YTypeOptions = [
  { key: "temp", label: "温度", unit: "°C", disabled: false },
  { key: "press", label: "压力", unit: "MPa", sdisabled: false },
  { key: "opening", label: "开度", unit: "%", disabled: false }
];

const deviceOptions = [[], []];

// let Alldevices = [];

// const getDeviceOptions = async () => {
//   try {
//     const tempData = await listDevices();
//     Alldevices = tempData.data.map(obj => {
//       return { devId: obj.id, name: obj.name, model: obj.model };
//     });
//     console.log(deviceOptions);
//   } catch (error) {
//     ElMessage.error("获取设备数据失败");
//   }
// };
// getDeviceOptions();

const props = defineProps({
  currentIndex: {
    type: Number,
    default: 0
  },
  visible: {
    type: Boolean,
    default: false
  },
  setting: {
    type: Object
  },
  defaultPointsNum: {
    type: Number
  },
  configId: {
    type: String,
    default: ""
  }
});
const emit = defineEmits([
  "update:visible",
  "update:setting",
  "data-confirm-click"
]);

const lastValue = ref(["", ""]);

const formVisible = ref(false);

const settingRef = toRef(props, "setting");

const tempSetting = ref(defaultSetting);
tempSetting.value = JSON.parse(JSON.stringify(props.setting));

const addSensor = Yindex => {
  tempSetting.value.optionY[Yindex].sensors.push({
    deviceId: "",
    name: "",
    period: 1,
    disabled: true
  });
};

const resetSettings = () => {
  tempSetting.value = JSON.parse(JSON.stringify(settingRef.value));
};

const cancelClick = () => {
  resetSettings();
  formVisible.value = false;
};

const handleClose = () => {
  resetSettings();
  formVisible.value = false;
};

const handleDelete = (Yindex, deviceId) => {
  tempSetting.value.optionY[Yindex].sensors = tempSetting.value.optionY[
    Yindex
  ].sensors.filter(obj => {
    return obj.deviceId != deviceId;
  });
  const foundObject = deviceOptions[Yindex].find(obj => {
    console.log(obj);
    return obj.devId === deviceId;
  });
  if (foundObject) {
    foundObject.disabled = false;
  }
};

const handleSelectChange = (value, scope, Yindex) => {
  let previousValue = "";

  previousValue = scope.row;
  console.log(previousValue);

  //如果没有，就选中，如果有就先取消选中
  console.log(deviceOptions[Yindex]);

  const previousObject = deviceOptions[Yindex].find(obj => {
    return obj.name === previousValue.name;
  });
  if (previousObject) {
    previousObject.disabled = false;
  }

  scope.row.name = deviceOptions[Yindex].find(obj => {
    return obj.devId === value;
  }).name;

  const foundObject = deviceOptions[Yindex].find(obj => {
    return obj.devId === value;
  });
  if (foundObject) {
    foundObject.disabled = true;
  }
};

const confirmClick = async () => {
  for (let i = 0; i < 2; i++) {
    for (const sensor of tempSetting.value.optionY[i].sensors) {
      await addPlatformDevice({
        expId: props.configId,
        deviceId: sensor.deviceId,
        interval: sensor.period
      });
    }
  }

  emit("update:setting", JSON.parse(JSON.stringify(tempSetting.value)));
  emit("data-confirm-click");
  console.log("emit");
  formVisible.value = false;
};

onMounted(async () => {
  for (let i = 0; i < 2; i++) {
    //找到类型对应的
    const foundObject = YTypeOptions.find(obj => {
      return obj.label === tempSetting.value.optionY[i].mesure;
    });
    foundObject.disabled = true;

    //列出该类型的所有设备
    const tempData = await listDevicesByMeasure(foundObject.key, "false");
    const deviceStatus = await listDeviceStatus();

    //筛选出在线的设备
    const resultArray = tempData.data.filter(obj1 => {
      // 在array2中查找与obj1相同id的对象，并且状态为1
      return deviceStatus.data.some(
        obj2 => obj2.deviceId === obj1.id && obj2.onlineState === 1
      );
    });

    deviceOptions[i] = resultArray.map(obj => {
      return { devId: obj.id, name: obj.name, model: obj.model };
    });

    for (const sensor of tempSetting.value.optionY[i].sensors) {
      const foundObject = deviceOptions[i].find(obj => {
        return obj.devId === sensor.deviceId;
      });
      if (foundObject) {
        foundObject.disabled = true;
      }
    }
  }
});

const handleChangeType = async (value, Yindex) => {
  console.log("lastValue.value[index]", lastValue.value[Yindex]);
  const previousType = YTypeOptions.find(obj => {
    return obj.label === lastValue.value[Yindex];
  });
  if (previousType) {
    previousType.disabled = false;
  }

  if (!value) {
    deviceOptions[Yindex] = [];
    return;
  }
  const foundObject = YTypeOptions.find(obj => {
    return obj.key === value;
  });
  foundObject.disabled = true;

  tempSetting.value.optionY[Yindex].mesure = foundObject.label;
  tempSetting.value.optionY[Yindex].unit = foundObject.unit;

  console.log(value);

  if (
    tempSetting.value.optionY[Yindex].mesure ==
    tempSetting.value.optionY[Number(!Yindex)].mesure
  ) {
    deviceOptions[Yindex] = deviceOptions[Number(!Yindex)];
    tempSetting.value.optionY[Yindex].sensors = [];
    for (const sensor of tempSetting.value.optionY[Yindex].sensors) {
      const foundObject = deviceOptions[Yindex].find(obj => {
        return obj.devId === sensor.deviceId;
      });
      if (foundObject) {
        foundObject.disabled = false;
      }
    }
    return;
  }

  try {
    const tempData = await listDevicesByMeasure(value, "false");
    const deviceStatus = await listDeviceStatus();

    const resultArray = tempData.data.filter(obj1 => {
      // 在array2中查找与obj1相同id的对象，并且状态为1
      return deviceStatus.data.some(
        obj2 => obj2.deviceId === obj1.id && obj2.onlineState === 1
      );
    });

    deviceOptions[Yindex] = resultArray.map(obj => {
      return { devId: obj.id, name: obj.name, model: obj.model };
    });
    tempSetting.value.optionY[Yindex].sensors = [];
    for (const sensor of tempSetting.value.optionY[Yindex].sensors) {
      const foundObject = deviceOptions[Yindex].find(obj => {
        return obj.devId === sensor.deviceId;
      });
      if (foundObject) {
        foundObject.disabled = false;
      }
    }
  } catch (error) {
    ElMessage.error("获取设备数据失败");
  }
};

watch(
  () => formVisible.value,
  val => {
    emit("update:visible", val);
  }
);

watch(
  () => props.visible,
  val => {
    formVisible.value = val;
  }
);

// watch(
//   () => props.setting,
//   val => {
//     console.log("watchINS1", val);
//     tempSetting.value = JSON.parse(JSON.stringify(val));
//   }
// );

// watch(props.setting, val => {
//   console.log("watchINS2", val);
//   tempSetting.value = JSON.parse(JSON.stringify(val));
//   console.log("监听父组件的setting，更新tempSetting", tempSetting.value);
// });
watch(
  () => settingRef.value.name,
  val => {
    console.log("name变化，更新数据", val);
    // emit("update:settingLine", JSON.parse(JSON.stringify(settingRef.value)));
    emit("data-confirm-click");
  }
);
watch(
  () => props.setting.duration,
  val => {
    console.log(val);
    tempSetting.value = props.setting;
    console.log("监听父组件的duration，更新tempSetting", tempSetting.value);
  }
);
</script>

<template>
  <el-drawer v-model="formVisible" :before-close="handleClose" direction="rtl">
    <template #header>
      <h4>{{ tempSetting.name }} 配置选项</h4>
    </template>

    <template #default>
      <div style="display: flex">
        <h3>{{ tempSetting.name }}</h3>
        <el-popover placement="right" :width="400" trigger="click">
          <template #reference>
            <IconifyIconOnline
              style="cursor: pointer"
              icon="material-symbols:edit-outline-rounded"
            />
          </template>
          <el-input
            v-model="tempSetting.name"
            :placeholder="tempSetting.name"
          />
        </el-popover>
      </div>

      <div class="optionContainer">
        <div
          class="YBox"
          v-for="(optionY, Yindex) in tempSetting.optionY"
          :key="Yindex"
        >
          <div class="TypeContainer">
            <div>{{ optionY.name }}坐标</div>
            <div>
              <el-select
                v-model="optionY.mesure"
                @click="lastValue[Yindex] = optionY.mesure"
                class="m-2"
                placeholder="未配置"
                size="default"
                clearable
                @change="handleChangeType(optionY.mesure, Yindex)"
              >
                <el-option
                  v-for="item in YTypeOptions"
                  :key="item.key"
                  :label="item.label"
                  :value="item.key"
                  :disabled="item.disabled"
                />
              </el-select>
            </div>
          </div>
          <el-table :data="optionY.sensors" style="width: 100%">
            <el-table-column
              header-align="center"
              align="center"
              prop="name"
              label="参数"
              width="140px"
            >
              <template #default="scope">
                <el-select
                  v-model="scope.row.deviceId"
                  class="m-2"
                  placeholder="未配置"
                  size="small"
                  @change="
                    handleSelectChange(scope.row.deviceId, scope, Yindex)
                  "
                >
                  <el-option
                    v-for="item in deviceOptions[Yindex]"
                    :key="item.devId"
                    :label="item.name"
                    :value="item.devId"
                    :disabled="item.disabled"
                  /> </el-select
              ></template>
            </el-table-column>
            <el-table-column
              header-align="center"
              prop="period"
              align="center"
              label="采样时间"
            >
              <template #default="scope">
                <div
                  style="
                    display: flex;
                    align-items: center;
                    justify-content: center;
                  "
                >
                  <el-input
                    v-model="scope.row.period"
                    style="width: 35px; margin-right: 5px"
                    placeholder="5"
                    size="small"
                  /><span>秒</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              header-align="center"
              align="center"
              prop="operate"
              label="操作"
            >
              <template #header>
                <el-button
                  type="primary"
                  size="small"
                  @click="addSensor(Yindex)"
                  circle
                  >+</el-button
                >
              </template>
              <template #default="scope">
                <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(Yindex, scope.row.deviceId)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!-- {{ deviceOptions }} -->
      <!-- <div>{{ settingRef }}</div>
      <div>{{ tempSetting }}</div> -->
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelClick">取消</el-button>
        <el-button type="primary" @click="confirmClick()">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<style lang="scss" scoped>
.TypeContainer {
  display: flex;
  flex-direction: row;
  align-items: center;
  font-size: 16px;
}

.YBox {
  margin-bottom: 50px;
}

.el-switch {
  margin: 0 !important;
}
</style>
